// pages/recurePlan.js
import request from '../../utils/request.js'
import {getRecommendationAddress, setAddress, APPID, SECRET, template_id} from '../../utils/settings.js'
const app = getApp()
let backgroundAudioManager = wx.getBackgroundAudioManager()
const plugin = requirePlugin("WechatSI")
const manager = plugin.getRecordRecognitionManager()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo:{},
    groupTimes: "",
    livingAdaptTarget: "",
    recureMethods: [],
    selfLivingTarget: "",
    sportTarget: "",
    strength: "",
    trainingProjects: [],
    hasPlan: false,
    hasRecord: false,
    hasScore: false
  },

  readPlan: function(){
    //读出此页面
    var playText = "我们为您推荐以下康复计划。。"+"运动康复目标："+this.data.sportTarget+"。生活自立能力康复目标："+this.data.selfLivingTarget+"。生活适应能力康复目标："+this.data.livingAdaptTarget+"。康复训练项目："
    for(let i = 0; i<this.data.trainingProjects.length; i++)
      playText = playText + this.data.trainingProjects[i] + "，"
    playText = playText +"。康复疗法："  
    for(let i = 0; i<this.data.recureMethods.length; i++)
      playText = playText + this.data.recureMethods[i] + "，"
    playText = playText +"。康复训练强度："+this.data.strength+"。康复训练组数："+this.data.groupTimes
    this.playsound(playText)
  },
  //文字转语音
  playsound:async function(con) {
    plugin.textToSpeech({
      lang: "zh_CN",
      tts: true,
      content: con,
      success: function(res) {
          console.log("succ tts", res.filename)  
          backgroundAudioManager.src = res.filename
          backgroundAudioManager.title = con
      },
      fail: function(res) {
          console.log("fail tts", res)
      }
    })
  },
  submitAgain:async function () {
    var that = this
    let thisUserInfo = wx.getStorageSync("userInfo")
    if(!thisUserInfo){
      wx.showToast({
        title: '请先进行身体评估',
        icon: 'error'
      })
    }
    let evaluation = thisUserInfo.score
    evaluation.evaluateStage =thisUserInfo.record.behaviorPhase
    console.log(evaluation)
    let dataset = {
      "sex": thisUserInfo.record.gender,
      "age": thisUserInfo.record.age,
      "disabilityType": thisUserInfo.record.disabilityType,
      "disabilityCause": thisUserInfo.record.disabilityCause,
      "disabilityLevel": thisUserInfo.record.disabilityLevel,
      "evaluation": evaluation
    }
    wx.request({
      url: getRecommendationAddress,
      data: dataset,
      method: "POST",
      success:(res)=>{
        that.data.userInfo.plan = res.data
        wx.request({
          url: setAddress,
          data: this.data.userInfo,
          method: "POST",
          success:(res)=>{
            
            wx.setStorageSync("userInfo", that.data.userInfo)
            that.onShow()
          },
          fail:(err)=>{
            wx.showToast({
              title: '保存失败',
              icon: 'error'
            })
            console.log(err)
          }
        })
        
        
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onShow:async function (options) {
    var that = this
    console.log(wx.getStorageSync("userInfo").plan)
    wx.getStorage({
      key: 'userInfo',
      success(res){
        console.log(res)
        that.setData({
          groupTimes: res.data.plan.groupTimes,
          livingAdaptTarget: res.data.plan.livingAdaptTarget,
          recureMethods: res.data.plan.recureMethods,
          selfLivingTarget: res.data.plan.selfLivingTarget,
          sportTarget: res.data.plan.sportTarget,
          strength: res.data.plan.strength,
          trainingProjects: res.data.plan.trainingProjects,
          userInfo: res.data
        })
      }
    })
    //当用户修改了档案或评分，询问是否重新获取
    let changed = wx.getStorageSync('changed')
    if(changed == 1){
        wx.setStorageSync('changed', 0)
        wx.showModal({
        title: '提示',
        content: '检测到您的身体评估数据发生了变化，是否重新获取康复信息？',
        success: function (res) {
          if (res.confirm) {//这里是点击了确定以后
            that.submitAgain()
          } else {//这里是点击了取消以后
            console.log('不重新获取')
          }
        }
      })
    }
    
  },

  submitMessage:async function(){
    //以下请求订阅消息
    let data = {grant_type:"client_credential",appid: APPID, secret: SECRET}
    let access_token = await request("https://api.weixin.qq.com/cgi-bin/token", data, "GET")
    console.log(access_token)
    await wx.requestSubscribeMessage({
      tmplIds: [template_id],
      success (res){
        console.log('res')
        console.log(res)
      }
    })
    let myDate = new Date()
    let userInfo = wx.getStorageSync('userInfo')
    let data2 = {touser: userInfo['openid'] ,
                template_id: template_id,
                data:{
                  "time11":{"value":myDate.toLocaleDateString()},
                    time5:{"value":myDate.getHours()+":"+myDate.getMinutes()},
                    thing7:{"value":"请不要忘记执行今天的训练计划哦"},
                    thing9:{"value":userInfo.plan.recureMethods.join(', ').substr(0,18)+"等"},
                    thing10:{"value":userInfo.plan.groupTimes},}}

    //执行下方语句即发送消息
    let submsg = await request("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token="+access_token.access_token, data2, "POST")
    console.log(submsg)


  },

})